package cc.liyinghao.springsecuritydemo.security.filter;


import cc.liyinghao.springsecuritydemo.security.util.JwtTokenUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    // 请求头前缀
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    // token前缀
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String authHeader = request.getHeader(this.tokenHeader);
        //token不为空且以Bearer开头
        if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
            // 获取"Bearer "后面的部分
            String authToken = authHeader.substring(this.tokenHead.length());
            // 从token中获取用户名
            String username = jwtTokenUtil.getUserNameFromToken(authToken);
            log.info("checking username:{}", username);
            // 用户名不为空 且 SecurityContextHolder中的Authentication为空
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                // 从数据库中根据用户名获取用户信息 userDetailsService 在单独的包中@Bean配置
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                // 验证token是否有效
                if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                    //打印当前用户的权限
                    System.out.println(userDetails.getAuthorities());

                    // 生成UsernamePasswordAuthenticationToken 目的是将用户信息放入SecurityContextHolder中
                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken
                                    (userDetails, null, userDetails.getAuthorities());
                    // 设置authentication的details 记录登录的IP和会话信息
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    log.info("authenticated user:{}", username);
                    // 将authentication存入SecurityContextHolder
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }else {
            System.out.println("token为空");
        }
        //为空放行，因为之后有其他的过滤器
        filterChain.doFilter(request, response);
    }
}
